import { ajax } from '../../utils/index';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList: [
      {
        label: "待维修",
        value: 0
      },
      {
        label: "待处理",
        value: 1
      },
      {
        label: "处理中",
        value: 2
      },
      {
        label: "已完成",
        value: 3
      }
    ],
    selectTab: 0,
    list: [],

    showDialog: false,

    dialogText: '',
    dialogImage: '',

    updateId: '',

    // 0开始处理 1处理完成
    clickBtnType: 0,

    // 当前登录的是否是工作人员
    isWorker: false
  },

  getDialogImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        wx.uploadFile({
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          url: 'https://still-warm-weevil.ngrok-free.app/upload_file',
          success: (res) => {
            const { data } = res;
            const path = JSON.parse(data)[0].path;
            const _path = path.split('\\');

            const url = `https://still-warm-weevil.ngrok-free.app/${_path[0]}/${_path[1]}`;

            this.setData({
              dialogImage: url
            })
          },
        })
      }
    })

  },

  getDialogText(e) {
    this.setData({
      dialogText: e.detail.value
    })
  },

  toFinish(e) {
    const _id = e.currentTarget.dataset._id;
    this.setData({
      clickBtnType: 1,
      showDialog: true,
      updateId: _id
    })
  },

  handleDialogCancel() {
    this.setData({
      showDialog: false,
      dialogText: '',
      dialogImage: '',
      updateId: '',
    })
  },

  async handleDialogConfirm() {
    const { dialogText, dialogImage, updateId, clickBtnType } = this.data;
    if (dialogText.trim().length === 0 || dialogImage.trim().length === 0 || updateId.trim().length === 0) {
      wx.showToast({
        title: '存在必填项未填写',
        icon: 'none'
      })
      return;
    }

    let params = {
      _id: updateId,
    };

    if (clickBtnType == 0) {
      // 开始处理
      params.status = 2;
      params.start_info = {
        text: dialogText,
        image: dialogImage
      }
    } else {
      // 处理完成
      params.status = 3;
      params.finish_info = {
        text: dialogText,
        image: dialogImage
      }
    }

    const { data } = await ajax('/update_service_order_info', 'POST', params);

    if (data === 'success') {
      wx.showToast({
        title: '操作成功',
        icon: 'none'
      })

      await this.getOrderList();
      this.handleDialogCancel();
    } else {
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }


  },
  // 重新维修
  async toReRepair(e) {
    const res = await ajax('/fixed_order', 'POST', {
      _id: e.currentTarget.dataset._id,
      order_id: e.currentTarget.dataset.order_id,
    });
    if (res.data.code === 200) {
      wx.showToast({
        title: res.data.msg || '重新维修成功',
        icon: 'none'
      })
      // 成功后刷新页面
      this.getOrderList();
    } else {
      wx.showToast({
        title: '重新维修失败',
        icon: 'none'
      })
    }



  },
  // 撤销维修
 async toCancel(e) { 
    const res = await ajax('/delete_service_order', 'POST', {
      _id: e.currentTarget.dataset._id,
    
    });
    if (res.data === 'success') {
      wx.showToast({
        title: '撤销维修成功',
        icon: 'none'
      })
      // 成功后刷新页面
      this.getOrderList();
    } else {
      wx.showToast({
        title: '撤销维修失败',
        icon: 'none'
      })
    }
  },

  toStart(e) {
    const _id = e.currentTarget.dataset._id;
    this.setData({
      clickBtnType: 0,
      showDialog: true,
      updateId: _id
    })
  },

  toPreview(e) {
    const file = e.currentTarget.dataset.file;

    wx.previewImage({
      urls: file.map(item => item.url),
    })
  },

  toResult(e) {
    const info = e.currentTarget.dataset.info;
    const { status } = info;
    if (status !== 3) {
      return;
    }
    wx.navigateTo({
      url: '../repairResult/repairResult?info=' + JSON.stringify(info),
    })
  },

  onTabsClick(e) {
    this.setData({
      selectTab: e.detail.value
    })
    this.getOrderList();
  },

  async getOrderList() {
    const { selectTab } = this.data;
    const { user_id, role } = wx.getStorageSync('loginInfo');
    if (!user_id) {
      return;
    }

    let params = {
      status: selectTab
    }

    if (role === 0) {
      params.user_id = user_id;
    } else if (role === 1) {
      params.worker_user_id = user_id;
    }

    const statusMap = {
      0: '待维修',
      1: '待处理',
      2: '处理中',
      3: '已完成'
    };

    const faultTypeMap = {
      0: '水电',
      1: '电器故障',
      2: '照明问题',
      3: '其它'
    }

    const { data: { result } } = await ajax('/get_service_order_list', 'POST', params);

    if (typeof result === 'object') {
      this.setData({
        list: result.map(item => {
          return {
            ...item,
            status_text: statusMap[item.status],
            fault_type_text: faultTypeMap[item.fault_type]
          }
        })
      })
    } else {
      wx.showToast({
        title: '服务器异常~',
        icon: 'none'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const loginInfo = wx.getStorageSync('loginInfo');
    const { role } = loginInfo;
    if (role === 1) {
      this.setData({
        tabList: [
          {
            label: "待处理",
            value: 1
          },
          {
            label: "处理中",
            value: 2
          },
          {
            label: "已完成",
            value: 3
          }
        ],
        selectTab: 1,
        isWorker: true
      })
    }
    this.getOrderList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})